﻿using System;
using System.Collections.Generic;
using Me.Prettyprint.Cassandra.Serializers;
using Me.Prettyprint.Cassandra.Service;
using Me.Prettyprint.Hector.Api;
using Me.Prettyprint.Hector.Api.Beans;
using Me.Prettyprint.Hector.Api.Factory;
using Me.Prettyprint.Hector.Api.Query;
using Org.Apache.Cassandra.Thrift;

namespace Me.Prettyprint.Cassandra.Model.Thrift
{
    /// <summary>
    /// ThriftCounterColumnQuery is used to query a counter column. For details on
    /// counter columns in Cassandra, please go to 
    /// http://www.datastax.com/documentation/cql/3.0/cql/cql_using/use_counter_t.html
    /// </summary>
    /// <typeparam name="K"></typeparam>
    /// <typeparam name="N"></typeparam>
    public class ThriftCounterColumnQuery<K, N> : AbstractBasicQuery<K, N, HCounterColumn<N>>, CounterQuery<K, N>
    {
        public ThriftCounterColumnQuery(Keyspace keyspace, Serializer<K> keySerializer,
            Serializer<N> nameSerializer)
            : base(keyspace, keySerializer, nameSerializer)
        {
        }

        public ThriftCounterColumnQuery(Keyspace keyspace)
            : base(keyspace, TypeInferringSerializer<K>.Instance, TypeInferringSerializer<N>.Instance)
        {
        }
        public CounterQuery<K, N> SetKey(K key)
        {
            Key = key;
            return this;
        }
        public CounterQuery<K, N> SetName(N name)
        {
            Name = name;
            return this;
        }
        public new CounterQuery<K, N> SetColumnFamily(string cf)
        {
            return (CounterQuery<K, N>) base.SetColumnFamily(cf);
        }
        public K Key
        {
            get;
            set;
        }
        public N Name
        {
            get;
            set;
        }
        public override QueryResult<HCounterColumn<N>> Execute()
        {
            Func<KeyspaceService, HCounterColumn<N>> x = (KeyspaceService ks) =>
            {
                CounterColumn thriftColumn = ks.GetCounter(KeySerializer.ToByteBuffer(Key).GetBuffer(),
                    ThriftFactory.CreateColumnPath(ColumnFamilyName, Name, ColumnNameSerializer));
                return new HCounterColumnImpl<N>(thriftColumn, ColumnNameSerializer);
            };
            return new QueryResultImpl<HCounterColumn<N>>(
                Keyspace.DoExecute(new KeyspaceOperationCallbackBuilder<HCounterColumn<N>>(x)), this);
        }
    }
}
